package cn.com.infcn.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.com.infcn.service.MssServiceI;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * MSP搜索接口调用
 */
@Controller
@RequestMapping("/portal/mss")
@Api(value = "MSP搜索接口调用", description = "MSP搜索接口调用!")
public class MssController {

	@Autowired
	private MssServiceI mssService;
	@Value("${mss_db}")
	private String tableNames;


	@RequestMapping("/getFenLei")
	@ResponseBody
	@ApiOperation(value = "根据搜索条件获取分类信息", httpMethod = "GET", notes = "根据搜索条件获取分类信息")
	public JSONObject getFenLei(
			// 搜索条件和分类条件
			@ApiParam(name = "userId", value = "用户ID", required = true) @RequestParam(required = true) String userId,
			@ApiParam(name = "keyWord", value = "搜索关键词", required = false) @RequestParam(required = false, defaultValue = "") StringBuilder keyWord,
			@ApiParam(name = "searchType", value = "搜索类型:0公共文件,1个人文件", required = true, defaultValue = "0") @RequestParam(required = true) String searchType,
			@ApiParam(name = "searchFields", value = "搜索范围如title,content", required = true, defaultValue = "title,content") @RequestParam(required = true, defaultValue = "title,content") String searchFields,

			// 分面条件
			@ApiParam(name = "field", value = "field", required = false, defaultValue = "") @RequestParam(required = false) String field,
			// msp分面参数,query、filter、field程序处理
			@ApiParam(name = "featchSize", required = false, defaultValue = "100") @RequestParam(required = false, defaultValue = "100") String featchSize,
			@ApiParam(name = "size", value = "分面的个数", required = false, defaultValue = "15") @RequestParam(required = false, defaultValue = "15") int size) {

		JSONObject returnObject = new JSONObject();
		try {

			// 2.处理搜索条件和过滤_start
			StringBuilder query = new StringBuilder();
			StringBuilder filter = new StringBuilder();
			dealCondition(userId, "", keyWord, searchType, query, filter, searchFields);

			// StringBuilder file_typeFilters = new
			// StringBuilder(filter.toString());//
			// 文件的filter,排除空的即未分类的

			// if (StringUtils.isNotBlank(file_type)) {// 文件类型
			// String temp = " AND (" + "file_type:\"" + file_type + "\") ";
			// upload_yearFilters.append(temp);
			// }
			//
			// // 过滤为空的分面_start
			// file_typeFilters.append(" AND (NOT file_type:\"\")");
			// 过滤为空的分面_end

			// 3.处理获取分面的数据_start
			JSONObject fenmianDataObj = new JSONObject();
			fenmianDataObj.put(field, mssService.getFenleiForOne(tableNames, featchSize, size, query.toString(),
					filter.toString(), field));
			// 3.处理获取分面的数据_end

			// 4.处理返回值_start
			returnObject.put("fenmianDataObj", fenmianDataObj);
			// 4.处理返回值_end

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnObject;

	}

	@RequestMapping("/getFenMian")
	@ResponseBody
	@ApiOperation(value = "根据搜索条件获取分面信息", httpMethod = "GET", notes = "根据搜索条件获取分面信息")
	public JSONObject getFenMian(
			// 搜索条件和分类条件
			@ApiParam(name = "userId", value = "用户ID", required = true) @RequestParam(required = true) String userId,
			@ApiParam(name = "folderId", value = "目录ID(公共目录的ID)", required = false, defaultValue = "0") @RequestParam(required = false) String folderId,
			@ApiParam(name = "keyWord", value = "搜索关键词", required = false) @RequestParam(required = false, defaultValue = "") StringBuilder keyWord,
			@ApiParam(name = "searchType", value = "搜索类型:0公共文件,1个人文件", required = true, defaultValue = "0") @RequestParam(required = true) String searchType,
			@ApiParam(name = "searchFields", value = "搜索范围如title,content", required = true, defaultValue = "title,content") @RequestParam(required = true, defaultValue = "title,content") String searchFields,

			// 分面条件
			@ApiParam(name = "file_type", value = "文件类型", required = false, defaultValue = "") @RequestParam(required = false) String file_type,
			@ApiParam(name = "upload_year", value = "年", required = false, defaultValue = "") @RequestParam(required = false) Integer upload_year,
			// msp分面参数,query、filter、field程序处理
			@ApiParam(name = "featchSize", required = false, defaultValue = "100") @RequestParam(required = false, defaultValue = "100") String featchSize,
			@ApiParam(name = "size", value = "分面的个数", required = false, defaultValue = "15") @RequestParam(required = false, defaultValue = "15") int size) {

		JSONObject returnObject = new JSONObject();
		try {

			// 2.处理搜索条件和过滤_start
			StringBuilder query = new StringBuilder();
			StringBuilder filter = new StringBuilder();
			dealCondition(userId, folderId, keyWord, searchType, query, filter, searchFields);

			StringBuilder upload_yearFilters = new StringBuilder(filter.toString());// 年分面的filter,排除空的即未分类的
			StringBuilder file_typeFilters = new StringBuilder(filter.toString());// 文件的filter,排除空的即未分类的

			if (upload_year != null) {// 年
				String temp = " AND (upload_year:\"" + upload_year + "\") ";
				file_typeFilters.append(temp);
			}
			if (StringUtils.isNotBlank(file_type)) {// 文件类型
				String temp = " AND (" + "file_type:\"" + file_type + "\") ";
				upload_yearFilters.append(temp);
			}

			// 过滤为空的分面_start
			upload_yearFilters.append(" AND (NOT upload_year:\"\")");
			file_typeFilters.append(" AND (NOT file_type:\"\")");
			// 过滤为空的分面_end

			// 3.处理获取分面的数据_start
			JSONObject fenmianDataObj = new JSONObject();

			fenmianDataObj.put("upload_year", mssService.getFenleiForOne(tableNames, featchSize, size, query.toString(),
					upload_yearFilters.toString(), "upload_year"));
			fenmianDataObj.put("file_type", mssService.getFenleiForOne(tableNames, featchSize, size, query.toString(),
					file_typeFilters.toString(), "file_type"));
			// 3.处理获取分面的数据_end

			// 4.处理返回值_start
			returnObject.put("fenmianDataObj", fenmianDataObj);
			// 4.处理返回值_end

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnObject;

	}

	/**
	 * 
	 * 描述: 获取资源类型
	 *
	 * @return JsonResult
	 */
	@RequestMapping("/getDataList")
	@ResponseBody
	@ApiOperation(value = "获取获取资源类型", httpMethod = "GET", notes = "获取获取资源类型")
	public JSONObject getDataList(
			// 搜索条件和分类条件
			@ApiParam(name = "userId", value = "用户ID", required = true) @RequestParam(required = true) String userId,
			@ApiParam(name = "keyWord", value = "搜索关键词", required = false) @RequestParam(required = false, defaultValue = "") StringBuilder keyWord,
			@ApiParam(name = "searchType", value = "搜索类型:0公共文件,1个人文件", required = true, defaultValue = "0") @RequestParam(required = true) String searchType,
			@ApiParam(name = "searchFields", value = "搜索范围如title,content", required = true, defaultValue = "title,content") @RequestParam(required = true, defaultValue = "title,content") String searchFields,
			@ApiParam(name = "folderId", value = "目录ID(公共目录的ID)", required = false, defaultValue = "0") @RequestParam(required = false) String folderId,
			// 分面条件
			@ApiParam(name = "file_type", value = "文件类型", required = false, defaultValue = "") @RequestParam(required = false) String file_type,
			@ApiParam(name = "upload_year", value = "年", required = false, defaultValue = "") @RequestParam(required = false) Integer upload_year,
			// msp要的条件
			@ApiParam(name = "sort", value = "排序 pubyear|asc,_score|desc", required = false, defaultValue = "") @RequestParam(required = false, defaultValue = "") String sort,
			// msp要的条件
			@ApiParam(name = "pageNum", value = "要获取数据的页码", required = true, defaultValue = "1") @RequestParam(required = true, defaultValue = "1") int pageNum,
			@ApiParam(name = "size", value = "获取页的数据多少条", required = true, defaultValue = "10") @RequestParam(required = true, defaultValue = "10") int size,
			@ApiParam(name = "defaultOperator", value = "默认的运算符(默认or): and|or", required = true, defaultValue = "OR") @RequestParam(required = true, defaultValue = "OR") String defaultOperator,
			@ApiParam(name = "includes", value = "返回结果包含哪些", required = false, defaultValue = "") @RequestParam(required = false, defaultValue = "") String includes,
			@ApiParam(name = "excludes", value = "返回结果不包含哪些", required = false, defaultValue = "") @RequestParam(required = false, defaultValue = "") String excludes) {

		JSONObject resourceCategorys = new JSONObject();
		try {

			StringBuilder query = new StringBuilder();
			StringBuilder filter = new StringBuilder();

			dealCondition(userId, folderId, keyWord, searchType, query, filter, searchFields);

			String heighlight = MssServiceI.getHightLightStringByEqual(new String[] { keyWord.toString() },
					new String[] { "title|40", "content|200" });

			StringBuilder distinct = new StringBuilder();

			if (StringUtils.isNotBlank(file_type)) {
				filter.append(" AND (file_type:\"" + file_type + "\") ");
			}
			if (upload_year != null) {
				filter.append(" AND (upload_year:\"" + upload_year + "\") ");
			}

			resourceCategorys = mssService.findList(tableNames, pageNum, size, defaultOperator, query.toString(),
					filter.toString(), heighlight, includes, excludes, distinct.toString(), sort);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resourceCategorys;

	}

	/**
	 * 
	 * 描述: 获取推荐列表
	 *
	 * @return JsonResult
	 */
	@RequestMapping("/getTuiJianList")
	@ResponseBody
	@ApiOperation(value = "获取推荐的list", httpMethod = "GET", notes = "获取推荐的list")
	public JSONObject getTuiJianList(
			// 搜索条件和分类条件
			@ApiParam(name = "userId", value = "用户ID", required = true) @RequestParam(required = true) String userId,
			@ApiParam(name = "keyWord", value = "文章的标题", required = true) @RequestParam(required = true) StringBuilder keyWord,
			@ApiParam(name = "searchFields", value = "搜索范围如title", required = true, defaultValue = "title") @RequestParam(required = true, defaultValue = "title") String searchFields,

			// msp要的条件
			@ApiParam(name = "pageNum", value = "要获取数据的页码", required = true, defaultValue = "1") @RequestParam(required = true, defaultValue = "1") int pageNum,
			@ApiParam(name = "size", value = "获取页的数据多少条", required = true, defaultValue = "10") @RequestParam(required = true, defaultValue = "10") int size) {

		JSONObject returnJSONObject = new JSONObject();
		try {
			String searchType = "0";
			StringBuilder query = new StringBuilder();
			StringBuilder filter = new StringBuilder();
			dealCondition(userId, "", keyWord, searchType, query, filter, false, searchFields);

			returnJSONObject = mssService.findList(tableNames, query.toString(), filter.toString(), "", pageNum, size);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJSONObject;

	}

	/**
	 * 
	 * 描述: 获取主题列表
	 * 
	 * @param userId
	 * @param keyWord
	 * @param searchType
	 * @param searchFields
	 * @param pageNum
	 * @param size
	 * @return
	 */
	@RequestMapping("/getSubject")
	@ResponseBody
	@ApiOperation(value = "获取主题的list", httpMethod = "GET", notes = "获取主题的list")
	public JSONObject getSubject(
			// 搜索条件和分类条件
			@ApiParam(name = "userId", value = "用户ID", required = true) @RequestParam(required = true) String userId,
			@ApiParam(name = "keyWord", value = "主题的关键字", required = true) @RequestParam(required = true) StringBuilder keyWord,
			@ApiParam(name = "searchType", value = "搜索类型:0公共,1个人,2自己能看的包括个人和公共", required = true, defaultValue = "0") @RequestParam(required = true) String searchType,
			@ApiParam(name = "searchFields", value = "搜索范围如title,content", required = true, defaultValue = "title,content") @RequestParam(required = true, defaultValue = "title,content") String searchFields,
			// msp要的条件
			@ApiParam(name = "pageNum", value = "要获取数据的页码", required = true, defaultValue = "1") @RequestParam(required = true, defaultValue = "1") int pageNum,
			@ApiParam(name = "size", value = "获取页的数据多少条", required = true, defaultValue = "10") @RequestParam(required = true, defaultValue = "10") int size) {
		JSONObject returnJSONObject = new JSONObject();

		try {
			keyWord = new StringBuilder(keyWord.toString().replace(",", " "));
			keyWord = new StringBuilder(keyWord.toString().replace("，", " "));
			StringBuilder query = new StringBuilder();
			StringBuilder filter = new StringBuilder();
			dealCondition(userId, "", keyWord, searchType, query, filter, false, searchFields);
			String sort = "";
			String[] split = keyWord.toString().split(" ");

			String heighlight = MssServiceI.getHightLightStringByEqual(false, split,
					new String[] { "title|40", "content|230" });

			returnJSONObject = mssService.findList(tableNames, query.toString(), filter.toString(), heighlight, sort,
					pageNum, size);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJSONObject;

	}

	/**
	 * 
	 * 描述: 获取猜你喜欢列表
	 * 
	 * @param userId
	 * @param keyWordArray
	 * @param searchType
	 * @param searchFields
	 * @param pageNum
	 * @param size
	 * @return
	 */
	@RequestMapping("/getGuessYouLike")
	@ResponseBody
	@ApiOperation(value = "猜你喜欢的list", httpMethod = "GET", notes = "猜你喜欢的list")
	public JSONArray getGuessYouLike(
			// 搜索条件和分类条件
			@ApiParam(name = "userId", value = "用户ID", required = true) @RequestParam(required = true) String userId,
			@ApiParam(name = "keyWords", value = "主题的关键字", required = false) @RequestParam(required = false) String[] keyWords,
			@ApiParam(name = "historyTitles", value = "主题的关键字", required = false) @RequestParam(required = false) String[] historyTitles,
			@ApiParam(name = "searchType", value = "搜索类型:0公共,1个人", required = true, defaultValue = "0") @RequestParam(required = true) String searchType,
			@ApiParam(name = "searchFields", value = "搜索范围如title,content", required = true, defaultValue = "title,content") @RequestParam(required = true, defaultValue = "title,content") String searchFields,
			// msp要的条件
			@ApiParam(name = "pageNum", value = "要获取数据的页码", required = true, defaultValue = "1") @RequestParam(required = true, defaultValue = "1") int pageNum,
			@ApiParam(name = "size", value = "获取页的数据多少条", required = true, defaultValue = "10") @RequestParam(required = true, defaultValue = "10") int size) {
		JSONArray returnJSONArray = new JSONArray();
		JSONArray temp_returnJSONArray = new JSONArray();
		try {

			if(keyWords!=null) {
				for (String string : keyWords) {
					JSONObject JSONObject = new JSONObject();
					StringBuilder query = new StringBuilder();
					StringBuilder filter = new StringBuilder();
					StringBuilder keyWord = new StringBuilder(string);
					dealCondition(userId, "", keyWord, searchType, query, filter, false, searchFields);
					String sort = "";
					String heighlight = "";
					JSONObject = mssService.findList(tableNames, pageNum, size, "OR", query.toString(), filter.toString(),
							heighlight, "", "content", "", sort);
					temp_returnJSONArray.addAll(JSONObject.getJSONArray("rows"));
				}
			}

			if(historyTitles !=null) {
				for (String string : historyTitles) {
					JSONObject JSONObject2 = new JSONObject();
					StringBuilder query = new StringBuilder();
					StringBuilder filter = new StringBuilder();
					String substring = string.substring(0, string.lastIndexOf("."));
					StringBuilder keyWord = new StringBuilder(substring);
					dealCondition(userId, "", keyWord, searchType, query, filter, false, searchFields);
					String sort = "";
					String heighlight = "";
					JSONObject2 = mssService.findList(tableNames, pageNum, size, "OR", query.toString(), filter.toString(),
							heighlight, "", "content", "", sort);
					temp_returnJSONArray.addAll(JSONObject2.getJSONArray("rows"));
					
				}
			}

			for (Object object : temp_returnJSONArray) {
				JSONObject jsonObject = (JSONObject) object;
				if (jSONArrayIsContainsJSONObjectByPropertity(temp_returnJSONArray, "id", jsonObject.getString("id"))) {
					returnJSONArray.add(jsonObject);
				} else {
					continue;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnJSONArray;

	}

	/**
	 * 判断是否JSONArray中是否包含“property”为“propertyValue”的对象
	 * 
	 * @param jSONArray
	 * @param property
	 * @param propertyValue
	 * @return
	 */
	private boolean jSONArrayIsContainsJSONObjectByPropertity(JSONArray jSONArray, String property,
			String propertyValue) {

		for (Object object : jSONArray) {
			JSONObject jsonObject = (JSONObject) object;
			String string = jsonObject.getString(property);
			if (propertyValue.equals(string)) {
				return true;

			}
		}
		return false;
	}

	/**
	 * 描述: 处理条件(默认精确)
	 * 
	 * @param userId
	 *            用户ID
	 * @param folderId
	 *            公共目录ID
	 * @param searchType
	 *            搜索类型
	 * @param keyWord
	 *            搜索关键词
	 * @param query
	 * @param filter
	 * @param searchFields搜索范围
	 */
	@ApiIgnore
	private void dealCondition(String userId, String folderId, StringBuilder keyWord, String searchType,
			StringBuilder query, StringBuilder filter, String searchFields) {
		dealCondition(userId, folderId, keyWord, searchType, query, filter, true, searchFields);
	}

	/**
	 * 
	 * 描述: 处理条件
	 * 
	 * @param userId
	 *            用户ID
	 * @param folderId
	 *            公共目录ID
	 * @param keyWord
	 *            搜索关键词
	 * @param searchType
	 *            搜索类型
	 * @param query
	 * @param filter
	 * @param isJingQue
	 *            是否精确
	 * @param searchFields搜索范围
	 */
	@ApiIgnore
	private void dealCondition(String userId, String folderId, StringBuilder keyWord, String searchType,
			StringBuilder query, StringBuilder filter, boolean isJingQue, String searchFields) {

		if (query.toString().trim().startsWith("AND")) {
			query = new StringBuilder(query.toString().replaceFirst("AND", ""));
		}
		if (filter.toString().trim().startsWith("AND")) {
			filter = new StringBuilder(filter.toString().replaceFirst("AND", ""));
		}
		String queryStart = "";
		String filterStart = "";
		queryStart = query.toString().length() > 0 ? " AND" : "";
		filterStart = filter.toString().length() > 0 ? " AND" : "";
		if ("0".equals(searchType)) {// 公共目录
			filter.append(filterStart + " (user_ids:\"" + userId + "\")" +" AND (_exists_:pub_folder_id) AND NOT(pub_folder_id:\"\") ");
		} else if ("1".equals(searchType)) {// 个人目录(个人查询)
			folderId = null;
			filter.append(filterStart + " (manager_id:\"" + userId + "\")");
		}else if ("2".equals(searchType)) {//我的主题【查询私密和公开的】
			filter.append(filterStart + "( ((user_ids:\"" + userId + "\")" +" AND (_exists_:pub_folder_id) AND NOT(pub_folder_id:\"\")) ");
			filter.append(" OR (manager_id:\"" + userId + "\"))");
		}
		filter.append(" AND ( enabled:\"1\") ");
		
		queryStart = query.toString().length() > 0 ? " AND" : "";
		filterStart = filter.toString().length() > 0 ? " AND" : "";

		if (StringUtils.isNotBlank(folderId)) {
			filter.append(filterStart + " pub_folder_id:\"" + folderId + "\" ");
		}
		queryStart = query.toString().length() > 0 ? " AND" : "";
		filterStart = filter.toString().length() > 0 ? " AND" : "";

		if (keyWord.toString().length() > 0) {
			keyWord = new StringBuilder(MssServiceI.escape(keyWord.toString().toUpperCase()));
			if (isJingQue) {
				String[] split = searchFields.split(",");
				String temp = queryStart + "(";
				for (int i = 0; i < split.length; i++) {
					String string = split[i];
					if (i != split.length - 1) {
						temp += string + ":\"" + keyWord + "\" OR ";
					} else {
						temp += string + ":\"" + keyWord + "\"";
					}
				}
				temp += ") ";
				query.append(temp);

				// query.append(queryStart + "(title:\"" + keyWord + "\" OR
				// content:\"" +
				// keyWord + "\") ");
			} else {
				String[] split = searchFields.split(",");
				String temp = queryStart + "(";
				for (int i = 0; i < split.length; i++) {
					String string = split[i];
					if (i != split.length - 1) {
						temp += string + ":" + keyWord + " OR ";
					} else {
						temp += string + ":" + keyWord;
					}
				}
				temp += ") ";
				query.append(temp);
				// query.append(queryStart + "(title:" + keyWord + " OR
				// content:" + keyWord + ")
				// ");
			}
		} else {
			String[] split = searchFields.split(",");
			String temp = queryStart + "(";
			for (int i = 0; i < split.length; i++) {
				String string = split[i];
				if (i != split.length - 1) {
					temp += string + ":* OR ";
				} else {
					temp += string + ":*";
				}
			}
			temp += ") ";
			query.append(temp);
			// query.append(queryStart + "(title:* OR content:*) ");
		}

	}
}
